<template>
	<view class="wrapper">
		<form @submit="onSubmit">
			<view class="block">
				<view class="row">
					<text class="label">商户号：</text>
					<view class="picker box">
						<picker :disabled="!vdata.isAdd" :style="styleComputed('mchIndex')" name="mchIndex" class="input" :range="MCHS" range-key="mchName" :value="vdata.saveObject.mchIndex" @change="onMchChange">
							{{ vdata.saveObject.mchIndex !== null ? MCHS[vdata.saveObject.mchIndex].mchName : '请选择商户' }}
						</picker>
						<uni-icons type="down" color="#ddd"></uni-icons>
					</view>

				</view>
				<view class="row">
					<text class="label">商户头图：</text>
					<gzMchImg :mchImg="MCHS[vdata.saveObject.mchIndex].mchListImage" :mcc="MCHS[vdata.saveObject.mchIndex].mcc" class="input" style="width: 120rpx;"></gzMchImg>
				</view>
			</view>
			<view class="block">
				<view class="row">
					<text class="label">卡券名称：</text>
					<input class="input" name="couponName" v-model="vdata.saveObject.couponName" placeholder="请输入卡券名称"/>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">卡券使用面额：</text>
					<input class="input" name="payAmount" v-model="vdata.saveObject.payAmount" placeholder="请输入卡券使用面额" type="digit"/>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">卡券优惠面额：</text>
					<input class="input" name="couponPrice" v-model="vdata.saveObject.couponPrice" placeholder="请输入卡券优惠面额" type="digit"/>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">卡券张数：</text>
					<input class="input" name="couponNum" v-model="vdata.saveObject.couponNum" placeholder="请输入卡券张数" type="number"/>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">每人可领用次数：</text>
					<input class="input" name="everyoneMaxNum" v-model="vdata.saveObject.everyoneMaxNum" placeholder="请输入可领用次数" type="number"/>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">开始时间：</text>
					<view class="picker">
						<picker :style="styleComputed('startTime')" class="input" name="startTime" :start="dayjs().add(1,'days').format('YYYY-MM-DD')" :value="vdata.saveObject.startTime" mode="date" @change="(e) => onDateChange(e,'startTime')">
							{{ vdata.saveObject.startTime + ' 00:00:00' }}
						</picker>
						<image src="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/942a8279-7341-472e-8056-3474f24a25e6.png"></image>
					</view>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">结束时间：</text>
					<view class="picker">
						<picker :style="styleComputed('endTime')" class="input" name="endTime" :start="dayjs().format('YYYY-MM-DD')" :value="vdata.saveObject.endTime" mode="date" @change="(e) => onDateChange(e,'endTime')">
							{{ vdata.saveObject.endTime + ' 23:59:59' }}
						</picker>
						<image src="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/942a8279-7341-472e-8056-3474f24a25e6.png"></image>
					</view>
				</view>
				<view class="line"></view>
				<view class="row">
					<text class="label">手机验证码：</text>
					<view class="vc">
						<input class="input" name="code" v-model="vdata.saveObject.code" placeholder="请输入验证码" type="number"/>
						<button @click="getMchSmsCode" plain :disabled="vcConfig.disabled" :style="{ color: vcConfig.color, border: `2rpx solid ${vcConfig.color}` }">{{ vcConfig.text }}</button>
					</view>
				</view>
			</view>
		
			<view class="btn-wrap">
				<button form-type="submit" plain>确认发券</button>
			</view>
		</form>
	</view>
</template>

<script setup>
	import { reactive, ref, computed, onUnmounted } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import storageManage from '@/util/storageManage.js'
	import { $bindMchCcSendMsg, $mchCcSendCoupon, $mchActivityEditCoupon } from '@/http/apiManager.js'
	import numberUtil from '@/util/numberUtil.js'
	import $infoBox from '@/common/fun.js'
	import dayjs from 'dayjs'
	
	// 验证码相关配置
	const vcConfig = reactive({
		timer: null,	// 定时器
		text: '获取验证码',
		color: '#24c789',
		disabled: false,
	})
	/**
	 * 获取验证码 重置
	 */
	function originCode(){
		if(vcConfig.timer){
			clearInterval(vcConfig.timer)
		}
		vcConfig.text = '获取验证码'
		vcConfig.color = '#24c789'
		vcConfig.disabled = false
	}
	/**
	 * 获取验证码
	 */
	function getMchSmsCode(){
		// 发送验证码
		vcConfig.disabled = true
		vcConfig.text = '发送中...'
		vcConfig.color = '#999'
		$bindMchCcSendMsg({ mchNo: MCHS.value[vdata.saveObject.mchIndex].mchNo,flag:8 }).then(res => {
			vcConfig.text = "重新获取(60)"
			let holdTime = 59; //定义变量并赋值
			vcConfig.timer = setInterval(() => {
				if (holdTime <= 0) {
					originCode()
					return; //返回前面
				}
				vcConfig.text = "重新获取(" + holdTime + ")"
				holdTime--;
			}, 1000)
		}).catch(()=>{
			originCode()
		})
	}
	
	onUnmounted(()=>{
		// 页面卸载 清空定时器
		if(vcConfig.timer){
			clearInterval(vcConfig.timer)
		}
	})
	
	// 数据源
	const vdata = reactive({
		isAdd: true,
		saveObject: {
			mchIndex: '0',
			startTime: dayjs().add(1,'days').format('YYYY-MM-DD'),
			endTime: dayjs().add(1,'days').format('YYYY-MM-DD'),
		}
	})
	
	// 样式计算属性
	const styleComputed = computed(() => (key) => {
		if(vdata.saveObject[key] !== undefined && vdata.saveObject[key] !== null){
			return { color: '#333' }
		}
		return { color: '#a3a3a3' }
	})
	
	// 商户列表数据
	const MCHS = ref(storageManage.MCHS_CC())
	console.log('MCHS',MCHS);
	
	onLoad(({ couponInfo }) => {
		// 根据couponInfo判断是修改卡券还是创建卡券
		if(couponInfo){
			const { mchNo, payAmount, couponPrice, startTime, endTime } = JSON.parse(decodeURI(couponInfo))
			vdata.isAdd = false
			vdata.saveObject = {
				...JSON.parse(decodeURI(couponInfo)),
				payAmount: numberUtil.computeNumber(payAmount,'/',100).result,
				couponPrice: numberUtil.computeNumber(couponPrice,'/',100).result,
				startTime: dayjs(startTime).format('YYYY-MM-DD'),
				endTime: dayjs(endTime).format('YYYY-MM-DD'),
				mchIndex: mchIndexHandle(storageManage.MCHS_CC(),mchNo)
			}
		}
	})
	
	// 默认商户处理 mchs本地缓存商户已绑定的商户列表  mchNo本次要修改的商户号
	function mchIndexHandle(mchs,mchNo){
		let mchIndex = '0'
		mchs.forEach((item,index) => {
			if(item.mchNo === mchNo){
				mchIndex = index.toString()
			}
		})
		return mchIndex
	}
	
	// 商户列表选择事件
	function onMchChange({detail}){
		const { value } = detail
		if(value !== vdata.saveObject.mchIndex){
			vdata.saveObject.mchIndex = value
		}
	}
	// 时间选择事件
	function onDateChange({ detail },key){
		const { value } = detail
		if(value !== vdata.saveObject[key]){
			vdata.saveObject[key] = value
		}
	}
	
	const rules = {
		mchIndex: { message: '请选择商户', strict: false },
		couponName: { message: '请输入卡券名称', strict: false },
		payAmount: { message: '请输入卡券使用面额', strict: true, min: 0.1, minMessage: '卡券使用面额需大于0.1' },
		couponPrice: { message: '请输入卡券优惠面额', strict: true, min: 0.1, minMessage: '卡券优惠面额需大于0.1' },
		couponNum: { message: '请输入卡券张数', strict: true, min: 4, minMessage: '卡券张数最少5张' },
		everyoneMaxNum: { message: '请输入可领用次数', strict: true },
		startTime: { message: '请选择开始时间', strict: false },
		endTime: { message: '请选择结束时间', strict: false },
		code: { message: '请输入验证码', strict: false }
	}
	
	// 表单提交
	function onSubmit(e){
		const payload = JSON.parse(JSON.stringify(vdata.saveObject))
		// 请求数据处理
		const { startTime, endTime, payAmount, couponPrice, mchIndex, couponNum, everyoneMaxNum } = payload
		// 非空校验
		let flag = false
		for(let key in rules){
			// 非空校验
			if(rules[key].strict){
				if(payload[key] === undefined || payload[key] === null || Number(payload[key]) === 0){
					$infoBox.toast(rules[key].message)
					flag = true
					break
				}
			}else{
				if(payload[key] === undefined || payload[key] === null){
					$infoBox.toast(rules[key].message)
					flag = true
					break
				}
			}
			// 校验卡券名称长度
			if(key === 'couponName'){
				if(payload[key]?.length > 9){
					$infoBox.toast('卡券名称最长9个字符')
					flag = true
					break
				}
			}
			// 校验最小数值
			if(rules[key].hasOwnProperty('min')){
				if(Number(payload[key]) <= rules[key].min){
					$infoBox.toast(rules[key].minMessage)
					flag = true
					break
				}
			}
			
			// 校验卡券优惠金额与使用金额
			if(key === 'couponPrice'){
				if(Number(payAmount) <= Number(couponPrice)){
					$infoBox.toast('卡券使用金额应大于卡券优惠金额')
					flag = true
					break
				}
			}
			
			// 开始时间不能大于结束时间校验
			if(key === 'endTime'){
				if(dayjs(endTime).isBefore(dayjs(startTime))){
					$infoBox.toast('开始时间需要小于结束时间')
					flag = true
					break
				}
			}
		}
		if(flag) return
		Object.assign(payload,{
			startTime: startTime + ` 00:00:00`,
			endTime: endTime + ' 23:59:59',
			payAmount: numberUtil.computeNumber(numberUtil.getFloatNumber(payAmount,2),'*',100).result,
			couponPrice: numberUtil.computeNumber(numberUtil.getFloatNumber(couponPrice,2),'*',100).result,
			couponNum: Number(couponNum),
			everyoneMaxNum: Number(everyoneMaxNum),
			mchNo: MCHS.value[mchIndex].mchNo
		})
		
		if(vdata.isAdd){	// 新建卡券
			uni.showModal({
				title: '提示',
				content: '请确认是否创建卡券？',
				success({ cancel }) {
					if(cancel) return;
					uni.showLoading({ title: '创建中...', mask: true })
					$mchCcSendCoupon(payload).then(res => {
						$infoBox.toast('卡券创建成功！',{ mask: true, duration: 2000 })
						setTimeout(() => {
							uni.navigateBack()
						},2000)
					})
				}
			})
		}else{	// 修改卡券
			uni.showModal({
				title: '提示',
				content: '请确认是否修改卡券？',
				success({ cancel }) {
					if(cancel) return;
					uni.showLoading({ title: '修改中...', mask: true })
					$mchActivityEditCoupon(payload).then(res => {
						$infoBox.toast('卡券修改成功！',{ mask: true, duration: 2000 })
						setTimeout(() => {
							uni.navigateBack()
						},2000)
					})
				}
			})
		}
	}
</script>

<style lang="less" scoped>
	@bg-color: #F5F6FA;
	.wrapper{
		width: 100%;
		min-height: 100vh;
		background-color: @bg-color;
		padding: 24rpx 32rpx 184rpx;
		box-sizing: border-box;
		position: relative;
		
		form{
			.block{
				background-color: #fff;
				border-radius: 16rpx;
				padding: 34rpx 20rpx;
				
				.line{
					width: 100%;
					height: 4rpx;
					background-color: #DDDDDD;
					margin: 20rpx 0;
					opacity: 0.6;
				}
				
				.row{
					display: flex;
					padding: 16rpx 0;
					align-items: center;
					
					.label{
						min-width: 20%;
						flex-shrink: 0;
						font-size: 28rpx;
					}
					.vc{
						display: flex;
						align-items: center;
						button{
							width: initial;
							border: none;
							font-size: 28rpx;
							background-color: #fff;
							flex-shrink: 0;
							border-radius: 8rpx;
							padding: 5rpx 15rpx;
							line-height: initial;
						}
					}
					.input{
						font-size: 28rpx;
					}
					.picker{
						display: flex;
						align-items: center;
						.input{
							flex-grow: 1;
						}
						&.box{
							flex-grow: 1;
							border: 1rpx solid #DDDDDD;
							border-radius: 8rpx;
							padding: 10rpx 20rpx;
						}
						image{
							width: 28rpx;
							height: 28rpx;
							margin-left: 40rpx;
						}
					}
					input.input{
						
					}
				}
				
				
				
				&:nth-child(2){
					margin-top: 24rpx;
					.row{
						.label{
							min-width: 35%;
						}
					}
				}
			}
			
			.btn-wrap{
				position: fixed;
				bottom: 0;
				left: 0;
				padding: 12rpx 32rpx 68rpx;
				width: 100%;
				background-color: #fff;
				z-index: 99;
				box-sizing: border-box;
				button{
					width: 100%;
					padding: 22rpx 0;
					text-align: center;
					background-color: #24C789;
					border-radius: 45rpx;
					box-sizing: border-box;
					color: #fff;
					border: none;
					line-height: initial;
				}
			}
		}
	}
	
</style>